package com.example2016.cjj.servicedemo.MyDownloader;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.example2016.cjj.servicedemo.DownloadActivity;
import com.example2016.cjj.servicedemo.R;

/**
 * Created by CJJ on 2016/12/22.
 */

public class DownloadService extends Service {
    private static final String TAG = "DownloadService";

    private DownloadServiceBinder downloadServiceBinder = new DownloadServiceBinder();

    private DownloadTask downloadTask;


    private DownloadListener downloadListener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            //更新通知中的下载进度条
            getNotificationManager().notify(1,getNotification("Downloading...",progress));

           if(downloadServiceProgressListener !=null){
               downloadServiceProgressListener.onProgressChanged(progress);
           }
        }

        @Override
        public void onSuccess() {
            downloadTask=null;
            //下载成功时将前台服务通知关闭，并创建一个下载成功的通知。
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Success",-1));
            Toast.makeText(DownloadService.this, "Download Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            downloadTask=null;
            //下载失败时将前台服务通知关闭，并创建一个下载失败的通知。
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Failed",-1));
            Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            downloadTask=null;
            Toast.makeText(DownloadService.this, "Download Paused", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            downloadTask=null;
            stopForeground(true);
            Toast.makeText(DownloadService.this, "Download Canceled", Toast.LENGTH_SHORT).show();
        }


    };

    private DownloadServiceProgressListener downloadServiceProgressListener;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return downloadServiceBinder;
    }

    public  class DownloadServiceBinder extends Binder{

        public void startDownload(String url){
            //开始下载
            if(downloadTask ==null){
                downloadTask = new DownloadTask(downloadListener);
                downloadTask.execute(url);
                startForeground(1,getNotification("Downloading...",0));
                Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
            }

        }

        public void pauseDownload(){
            //暂停下载
            if(downloadTask!=null){
                downloadTask.pauseDownload();
            }

        }

        public void cancelDownload(){
            //取消下载
            if(downloadTask !=null){
                downloadTask.cancelDownload();
            }
        }

        /**
         * 获取当前Service的实例
         * @return
         */
        public DownloadService getService(){
            return DownloadService.this;
        }

    }

    //获取系统的通知管理器
    private NotificationManager getNotificationManager(){
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    //构建一个下载通知。
    private Notification getNotification(String title, int progress) {
        Intent intent = new Intent(this, DownloadActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        builder.setContentTitle(title);
        builder.setContentIntent(pendingIntent);
        if(progress>=0){
            //档progerss大于或等于0的时候，才需显示下载进度。
            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
        }

        return builder.build();
    }


    public void setDownloadServiceProgressListener(DownloadServiceProgressListener downloadServiceProgressListener) {
        this.downloadServiceProgressListener = downloadServiceProgressListener;
    }
}
